/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//function to validate input of registry account
var formValidate = function() {
	// creating the data object to be sent to backend
	$("#usernamesignuperror").css("display", "none");
	$("#emailsignuperror").css('display', 'none');
	var formdata = new FormData();
	var phone = $("#usernamesignup").val();
	var errorFlag = false;
	if (!isPhoneNumber(phone)) {
		$('#usernamesignuperror').text('Invalid Phone');
		$("#usernamesignuperror").css("display", "block");
		errorFlag = true;
	} else {

			$("#usernamesignuperror").css('display', 'none');
	}
	// email
	var email = $("#emailsignup").val();
	if (!isEmail(email)) {
		$('#emailsignuperror').text('Invalid Email');
		$("#emailsignuperror").css("display", "block");

		errorFlag = true;
	} else {
			$("#emailsignuperror").css('display', 'none');
	}
	// password
	var password = $("#passwordsignup").val();
	if (password == "" || password.length < 6) {
		$("#passwordsignuperror").css("display", "block");

		errorFlag = true;
	} else {
		formdata.append('passwordsignup', CryptoJS.MD5(password));
		$("#passwordsignuperror").css('display', 'none');
	}
	var password_confirm = $("#passwordsignup_confirm").val();
	if (password_confirm != password) {
		$("#passwordsignup_confirmerror").css("display", "block");
		// data[data.length]=new
		// param('passwordsignup_confirm',CryptoJS.MD5(password_confirm));
		errorFlag = true;
	} else {
		$("#passwordsignup_confirmerror").css('display', 'none');
	}

	if (errorFlag) {
		return;
	} else {
		//check phone and email if exist 
		checkAccount(phone, email);
	}
}

// function to get the data by setting url, filter, success function and error
// function
var checkAccount = function(phone, email) {
	// making the ajax call
	var formdata = new FormData();
	formdata.append('phone', phone);
	formdata.append('email', email);
	var xhr = new XMLHttpRequest();       

    xhr.open("GET","/login?action=checkaccount&phone="+phone+"&email="+email, true);

    xhr.send(formdata);

    xhr.onload = function(e) {

        if (this.status == 200) {
        	var data = $.parseJSON(this.responseText).data;
        	if (data.length > 0) {
				for ( var int = 0; int < data.length; int++) {
					if (data[int].phone == $("#usernamesignup").val()) {
						$('#usernamesignuperror').text('Phone is already existed!');
						$("#usernamesignuperror").css("display", "block");
					}
					if (data[int].email == $("#emailsignup").val()) {
						$('#emailsignuperror').text('Email is already existed!');
						$("#emailsignuperror").css('display', 'block');
					}
				}
			} else {
				// register account after validating
				register();
			}
        	
        }
    }; 
}





//get list of friends in facebook and insert
var insertFacebookFriends = function() {
	FB.api('/me/friends', function(response) {
	      if (response.data != null) {
	    	  var friends = response.data;
	    	  for ( var int = 0; int < friends.length; int++) {
				var array_element = friends[int];
				FB.api('/'+array_element.id, function(response) {
					if (response != null) {
						insertUser(response);
					}
				});
			}
			
	      }
	    });
}

var insertUser = function(user) {
//	  "id": "40512085", 
//	  "name": "Haley Rae", 
//	  "first_name": "Haley", 
//	  "last_name": "Rae", 
//	  "link": "https://www.facebook.com/haley.halford1", 
//	  "gender": "female", 
//	  "locale": "en_US", 
//	  "updated_time": "2013-12-26T22:30:15+0000", 
//	  "username": "haley.halford1"
	var dataString = '&id='+ user.id +
					'&fullname='+ user.name +
					'&link='+ user.link +
					'&birthday='+ user.birthday +
					'&interested_in='+ user.interested_in +
					'&gender='+ user.gender +
					'&relationship_status='+ user.relationship_status +
					'&timezone='+ user.timezone +
					'&gender='+ user.gender +
					'&verified='+ user.verified +
					'&email='+ user.email +
					'&updated_time='+ user.updated_time +
					'&locale='+ user.locale +
					'&phone='+ user.phone +
					'&username='+ user.username;
	$.ajax({
		url : "/user?action=INSERT"+dataString,
		type : "POST",
		data:user.id,
		success : function(data) {
			if (data == null) {
				Alert('Insert process has error.')
			}
		}
	});

}

var updateUser = function(user) {
	var dataString = '&id='+ user.id +
					'&fullname='+ user.name +
					'&link='+ user.link +
					'&birthday='+ user.birthday +
					'&interested_in='+ user.interested_in +
					'&gender='+ user.gender +
					'&relationship_status='+ user.relationship_status +
					'&timezone='+ user.timezone +
					'&gender='+ user.gender +
					'&verified='+ user.verified +
					'&email='+ user.email +
					'&updated_time='+ user.updated_time +
					'&locale='+ user.locale +
					'&phone='+ user.phone +
					'&username='+ user.username;
	$.ajax({
		url : "/user?action=UPDATE"+dataString,
		type : "POST",
		data:user.id,
		success : function(data) {
			if (data == null) {
				//alert('Insert process has error.')
			}
		}
	});

}

//Update profile
var updateProfile = function(){
	// creating the data object to be sent to backend
	 var data=new Array();
	// collecting the field values from the form
	 var formEleList = $('form#user-update-form').serializeArray();
	 for(var i=0;i<formEleList.length;i++){
		data[data.length]=new param(formEleList[i].name,formEleList[i].value);
	 }
		 
	 //setting action as PUT
	 data[data.length]=new param('action','UPDATE');
	 //making the ajax call
	 $.ajax({
			url : "/user",
			type : "POST",
			data:data,
			success : function(data) {
				//showHideCreate(entity,false);
				showMessage('Successfully updated', 'user');
			}
		});
	
}

var insertFacebookUser = function() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
    	if (response != null) {
    		// making the ajax call
    		var userId = response.id;
    		var formdata = new FormData();
    		formdata.append('id', response.id);
    		var xhr = new XMLHttpRequest();       

    	    xhr.open("GET","/login?action=getUser&id="+response.id, true);

    	    xhr.send(formdata);

    	    xhr.onload = function(e) {

    	        if (this.status == 200) {
    	        	if (this.responseText != null && this.responseText != '') {
    	        		var data = $.parseJSON(this.responseText).data;
        	        	if (data.length > 0) {
        	        		//inserted by one of their friends
        					if(data[0].located_time == null || data[0].located_time == '') {
        						//Step 01: update info
        						//Step 02: update position by go to your phone and download app to run for update
        						updateUser(response);
        						//insertFacebookFriends();
        						//alert('You need to login by phone');
        						
        					} else {
//        						alert('Go to main page');
        						
//        						$.cookie('useraccount', response.id, { expires: 14 });
//        						document.location.href = '/map.html';
        					}
        						
        				} else {
        					// Insert new user into database
        					insertUser(response);
        				}
        	        	$.cookie('useraccount', response.id, { expires: 14 });
						document.location.href = '/index.html';
					} else {
						$("#loginstatus").css("display", "block");
						$.cookie('useraccount', '', { expires: 14 });
						document.location.href = '/login.html';
					}
    	        }
    	    }; 
    	}
    		
      //console.log('Good to see you, ' + response.name + '.');
      //$('messageResponse').text('response.name');
    });
}

// determine input is phone number
var isPhoneNumber = function(input) {
	var phoneRe = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
	var digits = input.replace(/\D/g, "");
	return (digits.match(phoneRe) !== null);
}

// determine input is phone number
var isEmail = function(input) {
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	if (input == '' || !emailReg.test(input)) {
		return false;
	}
	return true;
}

//function to register user
var register = function() {
	var formdata = new FormData();
	var phone = $("#usernamesignup").val();
	var email = $("#emailsignup").val();
	var password = CryptoJS.MD5($("#passwordsignup").val());
	var xhr = new XMLHttpRequest();       

    xhr.open("POST","/login?action=PUT&phone="+phone+"&email="+email+"&password="+password, true);

    xhr.onload = function(e) {

        if (this.status == 200) {
        	document.location.href = '/default.html#tosuccess';
        } else {
        	alert("Error! please try it again");
        }
    }; 
    
    xhr.send(formdata);
}

//login system
var login = function() {
	var formdata = new FormData();
	var phone = $("#username").val();
	var password = CryptoJS.MD5($("#password").val());
	var xhr = new XMLHttpRequest();       

    xhr.open("GET","/login?action=login&phone="+phone+"&password="+password, true);

    xhr.onload = function(e) {

        if (this.status == 200) {
        	var data = $.parseJSON(this.responseText).data;
        	if (data.length > 0) {
        		$.cookie('useraccount', $('#username').val(), { expires: 14 });
        		var remember = $('#loginkeeping').is(':checked');
        		if (remember == true) 
                {
                    var phone = $('#username').val();
                    var password = $('#password').val();

                    // set cookies to expire in 14 days
                    $.cookie('phone', phone, { expires: 14 });
                    $.cookie('password', password, { expires: 14 });
                    $.cookie('remember', true, { expires: 14 });
                                 
                }
                else
                {
                    // reset cookies
                    $.cookie('email', null);
                    $.cookie('password', null);
                    $.cookie('remember', false);
                }

        		document.location.href = '/map.html';
			} else {
				$("#loginstatus").css("display", "block");
				$.cookie('useraccount', '', { expires: 14 });
			}
        	
        } else {
        	alert("Error! please try it again");
        	$.cookie('useraccount', '', { expires: 14 });
        }
    }; 
    
    xhr.send(formdata);
}